package com.qfedu.edu.seckill.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author xiaobobo
 * @title: AddTagFilter
 * @projectName cd-java-2404-seckill-parent
 * @description: 添加网关标识的过滤器 防止这个请求不是来自于网关 而是其他地方
 * @date 2025/1/13  14:58
 */
@Component
public class AddTagFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //在这里我们就需要向这个请求的请求头中添加标识
        //首先拿到这个对象
        ServerHttpRequest request = exchange.getRequest();
        //然后通过这个对象 创建一个新的对象
        ServerHttpRequest requestNew = request.mutate().header("gatewayTag", "gatewayTag").build();
        //将新的对象设置到 原始的请求中去
        ServerWebExchange exchangeNew = exchange.mutate().request(requestNew).response(exchange.getResponse()).build();
        return chain.filter(exchangeNew);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
